﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace LoadGenerator
{
    class SvrConf
    {
        int _port;
        String _hostname;

        public int port { get { return _port; } set { _port = value; } }
        public String hostname { get { return _hostname; } set { _hostname = value; } }
    }

    class ClientConnection : IDisposable
    {
        Socket _connect;
        IPHostEntry _host;
        IPEndPoint _address;

        public ClientConnection(SvrConf conf)
        {
            _host = Dns.GetHostEntry(conf.hostname);
            _address = new IPEndPoint(_host.AddressList[0], conf.port);
            _connect = new Socket(_address.AddressFamily, SocketType.Stream,
                ProtocolType.Tcp);
     //       Console.WriteLine("Connecting to server: " + conf.hostname);
            _connect.Connect(_address); //synchronous call
            Console.WriteLine("Connected to server: " + conf.hostname);
        }

        public int sendData(CommunicationData send)
        {
            if (_connect.Connected)
            {
                System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
       //         Console.WriteLine("Sending Data: " + enc.GetString(send.nextData()));
                int written = _connect.Send(send.nextData());
                Console.WriteLine("Sent Data: " + enc.GetString(send.nextData()) + "written length: " + written);
                return written;
            }
            else
                throw new Exception("Socket not connected.");
        }

        public int receiveData(CommunicationData data, int sz)
        {
            if (_connect.Connected)
            {
                System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
                byte[] buffer = new byte[sz];
                int received = _connect.Receive(buffer, sz, SocketFlags.None);
                Console.WriteLine("Received: " + enc.GetString(buffer));
                data.received(buffer, received);
                while (received < sz)
                {
                    int thislen = _connect.Receive(buffer, sz, SocketFlags.None);
                    received += thislen;
                    Console.WriteLine("Received: " + enc.GetString(buffer));
                    data.received(buffer, thislen);
                }
                return received;
            }
            else
                throw new Exception("Socket not connected");
        }

        public void Dispose()
        {
            if (_connect.Connected)
                _connect.Close();
        }
    }
}
